package com.fingard.dsp.bank.directbank.zyb11;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.helpers.YBTHelper;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.ConnState;
import com.fingard.net.FtpPortClient;
import com.fingard.net.FtpReceiver;
import com.fingard.net.MixFtp;
import com.fingard.net.SftpPortClient;
import com.fingard.text.StringHelper;

import java.io.BufferedReader;
import java.io.File;
import java.io.StringReader;
import java.text.MessageFormat;
import java.util.Date;


/**
 * 中原银保通
 */
public class ZYB11BatPayRec extends ZYB11Base implements IBatPayRec {
    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return d_BatPayRec(p_req1988);
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        return d_QryBatPayRec(p_req1998);
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {
        return d_BatPayRec(p_req9188);
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        return d_QryBatPayRec(p_req9198);
    }

    /**
     * 批量代收付提交
     *
     * @param p_reqBat 批量代收付请求对象
     * @return 批量代收付响应对象
     * @throws Exception
     */
    public RetAtsBatPayRec d_BatPayRec(ReqBatPayRec p_reqBat) throws Exception {
        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_reqBat.reqHeader);
        retAts.reqSeqID = p_reqBat.reqBatchNO;

        try {
            // 代收付文件内容
            StringBuilder sbFileContent = new StringBuilder();

            Date dayCutTime = getDayCutTime(p_reqBat.getPayDateTime());
            String paySendDate = Format.Date8Format.format(dayCutTime);

            // 文件明细
            while (p_reqBat.readRecord()) {
                if (sbFileContent.length() > 0) {
                    sbFileContent.append("\n");
                }

                String postScript = p_reqBat.readedDetail.askNumber;

                String certNum = p_reqBat.readedDetail.certNum;
                String oppAct = "";
                String oppName = "";
                if ("1988".equals(p_reqBat.reqHeader.transType)) {
                    oppAct = p_reqBat.readedDetail.recAct;
                    oppName = p_reqBat.readedDetail.recName;
                } else {
                    oppAct = p_reqBat.readedDetail.payAct;
                    oppName = p_reqBat.readedDetail.payName;
                }

                String sourceNoteCode = p_reqBat.readedDetail.sourceNoteCode;
                String certType = convertCertTypeToBank(p_reqBat.readedDetail.certType);

                String payAmt = p_reqBat.readedDetail.payAmount;
                String busType = "";
                if ("1988".equals(p_reqBat.reqHeader.transType)) {
                    busType = getBankConfig().getSetValue("busiType", "", "1988");
                } else {
                    busType = getBankConfig().getSetValue("busiType", "", "9188");
                }

                // 明细信息:流水号|客户姓名|证件号码|保单号|结算日期|金额|账号|证件类型|业务类型\n
                String tmpReqBodyDetail = MessageFormat.format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}", postScript, oppName, certNum , sourceNoteCode, paySendDate, payAmt, oppAct, certType, busType);
                sbFileContent.append(tmpReqBodyDetail);
            }
            WriteBankLogLn2("批次文件内容:\r\n" + sbFileContent.toString());

            // 上传文件保存本地: 险公司首字母缩写(4位)+8位日期+S+2位序号(由01开始)加后缀.txt
            String cdFlag = "S";
            if ("1988".equalsIgnoreCase(p_reqBat.reqHeader.transType)) {
                cdFlag = "F";
            }
            String batSeqNo = YBTHelper.getBatSeqNo(getTempFileDirectory(dayCutTime), 2);
            String tmpUploadFileName = bankFront.corpNo + paySendDate + cdFlag + batSeqNo + ".txt";
            String tmpLocalMarkPath = getTempFileDirectory(dayCutTime) + File.separator + tmpUploadFileName;
            WriteBankLogLn2("批次文件保存本机路径: " + tmpLocalMarkPath);

            String tmpSeqNoFilePath = getTempFileDirectory(dayCutTime) + File.separator + p_reqBat.reqBatchNO + ".txt";
            WriteBankLogLn2("批次序号文件保存本机路径: " + tmpSeqNoFilePath);
            FileHelper.writeFile(tmpSeqNoFilePath, batSeqNo, getCharset());

            if (FileHelper.existFile(tmpLocalMarkPath)) {
                retAts.respCode = "0";
                retAts.respInfo = "本地批次文件已上传,请勿重复上传!";
                retAts.reqSeqID = p_reqBat.reqBatchNO;
                retAts.transState = PaymentState.FAIL_Batch;
                retAts.payInfoCode = FailCode.E9981;
                retAts.writeRetToATS();
                return retAts;
            }
            FileHelper.writeFile(tmpLocalMarkPath, sbFileContent.toString(), getCharset());

            // 上送银保通服务器
            //FtpSet ftpSet = bankFront.getFtpSet("bat");
            //MixFtp mixFtp = new MixFtp(ftpSet);
            //FtpReceiver ftpReceiver = mixFtp.uploadFileToDir(tmpLocalMarkPath, ftpSet.upDir, tmpUploadFileName);
            
            // 上送FTP服务器
            FtpSet ftpSet = bankFront.getFtpSet("bat");
            String ftpUpFilePath = StringHelper.trimEnd(ftpSet.upDir, "/") + "/" + tmpUploadFileName;
            WriteBankLogLn("当日批次文件上传FTP服务器路径:" + ftpUpFilePath);
            FtpReceiver ftpReceiver = null;
            String requestType = getBankConfig().getValueAsString("requestType");
            if (requestType != null && "SFTP".equals(requestType)) {
                SftpPortClient sftpPortClient = new SftpPortClient(ftpSet);
                String sftpFilePath = StringHelper.trimEnd(ftpSet.upDir, "/") + "/" + tmpUploadFileName;
                ftpReceiver = sftpPortClient.uploadFile("", tmpLocalMarkPath, sftpFilePath);
                sftpPortClient.disconnect();
            } else {
                FtpPortClient ftpPortClient = new FtpPortClient(ftpSet);
                ftpPortClient.setLocalPassiveMode();
                ftpReceiver = ftpPortClient.uploadFile(tmpLocalMarkPath, tmpUploadFileName);
                ftpPortClient.disconnect();
            }
            
            retAts.respCode = "0";
            if (!ftpReceiver.isCompleted) {
                retAts.respCode = "-1";
                retAts.respInfo = ftpReceiver.connMsg;
            } else if (ConnState.FAIL.equals(ftpReceiver.connState)) {
                retAts.respInfo = "上传失败";
                retAts.transState = "BatchFailed";
                retAts.payInfoCode = "E9999";
            } else {
                retAts.respInfo = "上传成功";
                retAts.transState = "Uploaded";
                retAts.payInfoCode = "I4001";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeRetToATS();
        return retAts;
    }

    /**
     * 批量代收付状态查询
     *
     * @param p_reqQryBat
     * @return
     * @throws Exception
     */
    public RetAtsQryBatPayRec d_QryBatPayRec(ReqQryBatPayRec p_reqQryBat) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_reqQryBat.reqHeader);
        retAts.reqSeqID = p_reqQryBat.reqBatchNO;

        try {
            // 下载文件名命名规则:P+保险公司首字母缩写+8位日期+S+2位序号(由01开始), 加后缀.txt
            Date dayCutTime = getDayCutTime(p_reqQryBat.getBgnDateTime());
            String tmpPaySendDate = Format.Date8Format.format(dayCutTime);

            String tmpSeqNoFilePath = getTempFileDirectory(dayCutTime) + File.separator + p_reqQryBat.reqBatchNO + ".txt";
            WriteBankLogLn2("批次序号文件保存本机路径: " + tmpSeqNoFilePath);
            
            
            String cdFlag = "S";
            if (p_reqQryBat.reqHeader.isBatPay) {
                cdFlag = "F";
            }
            
            String batSeqNo = FileHelper.readFileText(tmpSeqNoFilePath, getCharset());
            String tmpDownFileName = "P" + bankFront.corpNo + tmpPaySendDate + cdFlag + batSeqNo + ".txt";
            String tmpLocalMarkPath = createTempFileDirectory(dayCutTime) + File.separator + tmpDownFileName;
            WriteBankLogLn2("批次结果文件保存本地路径: " + tmpLocalMarkPath);

            FtpSet ftpSet = bankFront.getFtpSet("bat");
            MixFtp mixFtp = new MixFtp(ftpSet);
            FtpReceiver ftpReceiver = mixFtp.downloadFileFromDir(ftpSet.downDir, tmpDownFileName, tmpLocalMarkPath);
            if (ftpReceiver.isCompleted) {
                String tmpStrRet = FileHelper.readFileText(tmpLocalMarkPath, getCharset());
                WriteBankLogLn2("本地批次结果文件内容:\r\n" + tmpStrRet);
                if (StringHelper.hasAnyChar(tmpStrRet)) {
                    retAts.respCode = "0";

                    StringReader strReader = new StringReader(tmpStrRet);
                    BufferedReader tmpReader = new BufferedReader(strReader);

                    while(true) {
                        String eachline = tmpReader.readLine();
                        if(StringHelper.isNullOrEmpty(eachline)){
                            break;
                        }
                        if (eachline.indexOf("|") > 0) {
                            String[] bodyValues = eachline.split("\\|");
                            RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                            if(p_reqQryBat.reqHeader.transType.equals("1998")){
                                tmpRetDetail.recAct = bodyValues[6];
                            } else if(p_reqQryBat.reqHeader.transType.equals("9198")){
                                tmpRetDetail.payAct = bodyValues[6];
                            }
                            tmpRetDetail.postScript = bodyValues[0];
                            tmpRetDetail.payAmount = StringHelper.amountDivide100(bodyValues[5]);
                            tmpRetDetail.result = bodyValues[7];
                            tmpRetDetail.payInfoCode = bodyValues[7];
                            tmpRetDetail.memo = bodyValues[8];

                            retAts.writeRetDetail(tmpRetDetail);
                        } else {
                            retAts.respCode = "-1";
                            retAts.respInfo = "银行返回明细数据格式非法!";
                        }
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "本地批次结果文件内容为空!";
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "结果文件下载失败:" + ftpReceiver.connMsg;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            retAts.respCode = "-1";
            retAts.respInfo = ex.getMessage();
            WriteBankLogLn(ex);
        }

        retAts.writeAfterDetail();
        return retAts;
    }
}